package cn.itcast.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.itcast.dao.RoleDao;
import cn.itcast.dao.UserDao;
import cn.itcast.dao.UserRoleDao;
import cn.itcast.entity.PageResult;
import cn.itcast.pojo.Role;
import cn.itcast.pojo.User;
import cn.itcast.service.UserService;
import cn.itcast.utils.DateUtils;
import cn.itcast.utils.MD5Utils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashSet;
import java.util.List;

/*@Transactional(readOnly = true)*/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRoleDao userRoleDao;

    /*
    * 根据id查询
    * */
    @Override
    public User selectByIdUser(Integer id) {
        User user = this.userDao.selectByIdUser(id);
        return user;
    }

    /*
    *查询用户下的角色id
    * */
    @Override
    public Integer[] selectRoleIds(Integer userId) {
        return this.userDao.selectRoleIds(userId);
    }

    /*
    * 根据关键字查询用户
    * */
    @Override
    public PageResult selectByNameUser(Integer currentPage, Integer pageSize, Long total, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        List<User> userList;
        if (StrUtil.isEmpty(queryString)){
            userList = this.userDao.selectUser();
        }else {
            userList = this.userDao.selectByNameUser(queryString);
        }
        return new PageResult(total,userList);
    }

    /*
     * 新增用户
     * */
    @Override
    public void saveUser(User user,Integer[] roleIds) {
        String md5 = MD5Utils.md5(user.getPassword());
        user.setPassword(md5);
        userDao.saveUser(user);
        if (roleIds != null){
            Integer userId = user.getId();
            this.setUserRoleId(userId,roleIds);
        }
    }

    /*
    * 根据id删除用户
    * */
    @Override
    public void deleteUser(Integer userId) {
        this.userDao.deleteUser(userId);
        this.userRoleDao.deleteUserRole(userId);
    }

    /*
    * 修改用户信息
    * */
    @Override
    public void updateUser(User user, Integer[] roleIds) {
        //转换密码
        String md5 = MD5Utils.md5(user.getPassword());
        user.setPassword(md5);
        //日期转换
        this.userDao.updateUser(user);
        //根据用户id删除中间表的角色id
        this.userRoleDao.deleteUserRole(user.getId());
        //给中间表添加id
        this.setUserRoleId(user.getId(),roleIds);
    }

    /*
     * 向中间表添加id
     * */
    private void setUserRoleId(Integer userId, Integer[] roleIds) {
        for (Integer roleId : roleIds) {
            this.userRoleDao.saveUserRole(userId,roleId);
        }
    }
}
